package com.shushan.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.android.fgchecker.AppChecker;
import com.shushan.db.GameTimeDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.lockscreen.bean.GameTimeBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.util.ControlUtil;
import com.shushan.util.SystemUtils;

import java.util.List;

/**
 * @ClassName: ForegroundRTAService
 * @Desciption: 前台应用监听服务
 * @author: yichaohua
 * @date: 2018-06-05
 */
public class ForegroundRTAService extends Service {

    private final static String TAG = "ForegroundRTAService";

    private AppChecker appChecker;
    private String allowPackName;
    private String allowAppLabel;
    private int paperId = 0;
    private GameTimeDao gameTimeDao;
    private boolean isWhitePlay;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG,"onCreate()");

        gameTimeDao = new GameTimeDao(this);

        startChecker();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(intent != null){
            boolean isStopSelf = intent.getBooleanExtra("isStopSelf",false);
            Log.i(TAG,"stopSelf=" + isStopSelf + " isWhitePlay=" + isWhitePlay);
            if(isStopSelf && !isWhitePlay){
                stopSelf();
                return super.onStartCommand(intent, flags, startId);
            }

            allowPackName = intent.getStringExtra("allowPackName");
            allowAppLabel = intent.getStringExtra("allowAppLabel");
            paperId = intent.getIntExtra("paperId",0);
            isWhitePlay = intent.getBooleanExtra("isWhitePlay",false);

            postStartGameTime(paperId,allowPackName,allowAppLabel);
        }

        Log.i(TAG,"paperId=" + paperId + " allowPackName=" + allowPackName +
                " allowAppLabel=" + allowAppLabel + " isWhitePlay=" + isWhitePlay);

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i(TAG,"onDestroy()");

        stopChecker();

        stopSelf();

        postEndGameTime(paperId,allowPackName);
    }

    private void startChecker() {
        appChecker = new AppChecker();
        appChecker.when(getPackageName(), new AppChecker.Listener() {
                    @Override
                    public void onForeground(String packageName) {
                        Log.i(TAG,"Our app is in the foreground.");
                    }
                })
                .whenOther(new AppChecker.Listener() {
                    @Override
                    public void onForeground(String packageName) {
                        Log.i(TAG,"allowPackName=" + allowPackName + " packageName=" + packageName
                            + " isGamesAvailable=" + GamesWindowManager.isIsGamesAvailable());
                        if(!TextUtils.isEmpty(allowPackName) &&
                                (ControlUtil.isOpenPack(BabyApplication.getInstance(),packageName)
                                        || allowPackName.equals(packageName))){
                            return;
                        }

                        postEndGameTime(paperId,allowPackName);

                        if(isWhitePlay){
                            stopSelf();
                            SystemUtils.sendForegActivity(BabyApplication.getInstance(),TabHomeActivity.class);
                        }else if (!GamesWindowManager.isIsGamesAvailable()){
                            GamesWindowManager.createGamesFloatWindow(BabyApplication.getInstance());
                        }

                    }
                })
                .timeout(3000)
                .start(this);
    }

    private void stopChecker() {
        appChecker.stop();
    }

    private void postStartGameTime(int paperId,String allowPackName,String allowAppLabel) {
        if(TextUtils.isEmpty(allowPackName)){
            Log.e(TAG,"postStartGameTime() 为空");
            return;
        }

        int currentChildId = BabyApplication.getInstance().getCurrentChildId();
        List<GameTimeBean> gameTimeBeanList = gameTimeDao.queryForPaperIdNow(paperId);
        if(gameTimeBeanList.size() == 0){
            addNewGameTime(paperId,allowPackName,allowAppLabel);
        }else if(!gameTimeDao.containChildId(currentChildId,gameTimeBeanList)){
            addNewGameTime(paperId,allowPackName,allowAppLabel);
        }else if(!gameTimeDao.containUsePage(allowPackName,gameTimeBeanList)){
            addNewGameTime(paperId,allowPackName,allowAppLabel);
        }else {
            GameTimeBean gameTimeBean = gameTimeDao.getGameTimeBean(currentChildId,allowPackName,gameTimeBeanList);
            if(gameTimeBean != null){
                Log.i(TAG,"setStartTime=" + System.currentTimeMillis() + " isOver=" + gameTimeBean.isOver());

                gameTimeBean.setStartTime(System.currentTimeMillis());
                gameTimeBean.setOver(false);
                gameTimeDao.update(gameTimeBean);
            }else {
                addNewGameTime(paperId,allowPackName,allowAppLabel);
            }
        }
    }

    private void postEndGameTime(int paperId,String allowPackName) {
        if(TextUtils.isEmpty(allowPackName)){
            Log.e(TAG,"postEndGameTime() 为空");
            return;
        }

        int currentChildId = BabyApplication.getInstance().getCurrentChildId();
        List<GameTimeBean> gameTimeBeanList = gameTimeDao.queryForPaperIdNow(paperId);
        if(gameTimeBeanList.size() == 0){
            Log.e(TAG,"postEndGameTime queryForPaperId == null");
        }else {
            GameTimeBean gameTimeBean = gameTimeDao.getGameTimeBean(currentChildId,allowPackName,gameTimeBeanList);
            if(gameTimeBean == null){
                Log.e(TAG,"postEndGameTime gameTimeBean == null");
            }else {
                long currentTime = System.currentTimeMillis();
                long startTime = gameTimeBean.getStartTime();
                long useTime = gameTimeBean.getUseTime() + currentTime - startTime;
                Log.i(TAG,"postEndGameTime currentTime=" + currentTime + " startTime="
                        + startTime + " useTime=" + useTime + " isOver=" + gameTimeBean.isOver());

                if(!gameTimeBean.isOver()){
                    gameTimeBean.setUseTime(useTime);
                    gameTimeBean.setStartTime(currentTime);
                    gameTimeBean.setOver(true);

                    gameTimeDao.update(gameTimeBean);
                }

            }
        }

        BabyApplication babyApplication = BabyApplication.getInstance();
        Intent intent2 = new Intent(babyApplication,PostGameTimeServer.class);
        babyApplication.startService(intent2);
    }

    private void addNewGameTime(int paperId,String allowPackName,String allowAppLabel){
        Log.i(TAG,"paperId=" + paperId + " allowPackName=" + allowPackName
                + " allowAppLabel=" + allowAppLabel);

        GameTimeBean postGameTimeBean = new GameTimeBean();
        postGameTimeBean.setPaperId(paperId);
        postGameTimeBean.setUsePackName(allowPackName);
        postGameTimeBean.setUseAppLabel(allowAppLabel);

        gameTimeDao.add(postGameTimeBean);

    }

}
